
import React from "react";
import { dictionary } from "@/modules";
import { ICapability } from "@/components/capability";
import { IconSelect } from "@/views/Development/ui/IconManage/IconSelect";
import { useVisible } from "@/tools/hooks";
import { Button, Drawer, Form, FormInstance, Input, InputNumber, Select, Space, Switch, TreeSelect } from "antd";
import { v4 as uuidv4 } from 'uuid';
import { MenuController } from "@/controllers/MenuController";

/** 编辑菜单 */
export function useEditMenu(record): ICapability {

    const formRef = React.useRef<FormInstance<any>>(null);

    const controller = React.useContext(MenuController.Context);

    const menu = controller.useMemo(s => s.menu);

    const menuTree = React.useMemo(() => {
        function ct(pid?: string) {
            return menu
                .filter(m => pid ? m.menuParentId === pid : !m.menuParentId)
                .sort((a, b) => (b.order || 0) - (a.order || 0))
                .map(m => ({ ...m, children: ct(m.menuId) }))
        }
        return ct();
    }, [menu])

    const { open, onClose, onOpen } = useVisible()

    const onFinish = React.useCallback(async (values) => {
        // const parent = menu.find(m => m.menuId === values.menuParentId);

        await controller.run(async s => {

            const level = record?.level || 0;

            s.menu = s.menu.filter(m => m.menuId !== record.menuId)
            s.menu = [...s.menu, { ...values, level }]

            // --- 更新子菜单的层级 ---
            // const childs: string[] = []
            // getChilds(s.menu.filter(m => m.menuId === record.menuId));
            // function getChilds(is: IMenu[]) {
            //     is.forEach(i => {
            //         childs.push(i.menuId)
            //         getChilds(s.menu.filter(m => m.menuParentId === i.menuId))
            //     })
            // }
            // childs.forEach(c => {
            //     s.menu.filter(m => m.menuId === c).forEach(m => m.level = level)
            // })
        })

        onClose()
    }, [controller, onClose, record?.level, record.menuId])

    const element = React.useMemo(() => {
        return (
            <Drawer
                title="编辑"
                onClose={onClose}
                open={open}
                footer={
                    <Space style={{ width: '100%', justifyContent: 'end' }} >
                        <Button onClick={onClose} >取消</Button>
                        <Button onClick={() => { formRef.current?.submit() }} type='primary' >保存</Button>
                    </Space>
                }
            >
                <Form
                    layout='vertical'
                    ref={formRef}
                    onFinish={onFinish}
                >
                    <Form.Item
                        label="名称"
                        name="menuName"
                        rules={[
                            { required: true, message: '请输入名称' },
                            { max: 20, message: '最多20个字符' }
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="ID"
                        name="menuId"
                        rules={[
                            { required: true, message: '请输入ID' },
                            { max: 20, message: '最多20个字符' },
                            { pattern: /^[a-zA-Z0-9]+$/, message: '只能是英文数字' },
                        ]}
                    >
                        <Input readOnly />
                    </Form.Item>

                    <Form.Item
                        label="父级"
                        name="menuParentId"
                        rules={[
                            {
                                validator: (_, value) => {
                                    if (value !== record.menuId) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('不能选择自己'));
                                },
                            },
                        ]}
                    >
                        <TreeSelect
                            allowClear
                            treeData={menuTree}
                            treeDefaultExpandAll
                            fieldNames={{ label: 'menuName', value: 'menuId' }}
                        />
                    </Form.Item>

                    <Form.Item
                        label="图标"
                        name="iconId"
                    >
                        <IconSelect block style={{ textAlign: 'left' }} >点击选择图标</IconSelect>
                    </Form.Item>

                    <Form.Item
                        label="是否隐藏"
                        name="isHide"
                    >
                        <Switch />
                    </Form.Item>

                    <Form.Item
                        label="模块"
                        name="moduleId"
                    >
                        <Select
                            allowClear
                            options={Array.from(dictionary.keys()).map(key => ({ label: dictionary.get(key)?.title, value: key }))}
                        />
                    </Form.Item>

                    <Form.Item
                        label="路径"
                        name="path"
                        rules={[
                            { max: 100, message: '最多100个字符' },
                            { pattern: /^\/[a-zA-Z0-9/?&=]*$/, message: '必须以 / 开头，且只能包含英文、数字、/?&=' }
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="层级"
                        name="level"
                        initialValue={0}
                    >
                        <InputNumber readOnly min={0} max={99999} style={{ width: "100%" }} />
                    </Form.Item>

                    <Form.Item
                        label="顺序"
                        name="order"
                        initialValue={0}
                    >
                        <InputNumber min={0} max={99999} style={{ width: "100%" }} />
                    </Form.Item>
                </Form>
            </Drawer>
        )
    }, [menuTree, onClose, onFinish, open, record.menuId])

    const onStart = onOpen;

    // 打开表达时候，重置表单
    React.useEffect(() => {
        if (!open) return
        formRef.current?.resetFields()
        formRef.current?.setFieldsValue(record)
    }, [open, record])

    return {
        id: uuidv4(),
        title: '编辑',
        element,
        onStart,
    }
}